﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using yncTech.BusinessObjects;
using yncTech.Common;

/// <summary>
/// MailReminder 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消注释以下行。 
// [System.Web.Script.Services.ScriptService]
public class MailReminder : System.Web.Services.WebService {

    public MailReminder () {

        //如果使用设计的组件，请取消注释以下行 
        //InitializeComponent(); 
    }


    const string MAIL_CONTENT = "<p>{0}您好：</p><p>您借阅的凭证({1})即将到期({2})，请准时归还。</p><p>系统邮件请不要回复！</p>";
    const string MAIL_CONTENT_EXPIRE = "<p>{0}您好：</p><p>您借阅的凭证({1})已到期({2})，请准时归还。</p><p>系统邮件请不要回复！</p>";

    /// <summary>
    /// 借阅到期邮件提醒
    /// </summary>
    /// <returns></returns>
    [WebMethod]
    public void ReturnReceiptReminder() {
        int reminderDays = int.Parse(ConfigurationManager.AppSettings["ReminderDay"]);

        FinLendCollection lends = new FinLendCollection();
        lends.Query.Where(lends.Query.LendStatus == (int)LendStatus.Lent && lends.Query.ReturnDate<=DateTime.Now.AddDays(reminderDays));
        lends.Query.Load();

       foreach(var item in lends)
       {
           FinLendReceiptQuery q1 = new FinLendReceiptQuery("q1");
           FinReceiptQuery q2 = new FinReceiptQuery("q2");
           q1.InnerJoin(q2).On(q1.ReceiptID == q2.ReceiptID);
           q1.Select(q2.DocumentsNo);
           q1.OrderBy(q2.DocumentsNo.Ascending);
           DataTable table = q1.LoadDataTable();
           string recs = string.Empty;
           foreach(DataRow dr in table.Rows )
           {
               recs += dr[0].ToString() + ",";
           }

           string mailBody = "";
           if (item.ReturnDate.Value.Date <= DateTime.Now.Date)
           {
               mailBody = string.Format(MAIL_CONTENT, item.Loanee, recs.TrimEnd(','), item.ReturnDate.Value.ToString(ConstantValue.DateFormat));
           }
           else
           {
               mailBody = string.Format(MAIL_CONTENT_EXPIRE, item.Loanee, recs.TrimEnd(','), item.ReturnDate.Value.ToString(ConstantValue.DateFormat));
           }

           SendMail.SendHtml(new string[] { item.LoaneeEmail }, "凭证借阅到期提醒", mailBody);
        }
        
    }
    
}
